<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="订单编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户" prop="cusName">
        <el-input
          v-model="queryParams.cusName"
          placeholder="请输入客户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总价" prop="total">
        <el-input
          v-model="queryParams.total"
          placeholder="请输入总价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="修改人" prop="updateBy">
        <el-input
          v-model="queryParams.updateBy"
          placeholder="请输入修改人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="修改时间">
        <el-date-picker
          v-model="daterangeUpdateDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xiaoshou:order:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['xiaoshou:order:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['xiaoshou:order:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['xiaoshou:order:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
      highlight-current-row
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column fixed prop="code" label="订单编号" width="150">
        <template slot-scope="scope">
          <orderView :data="scope.row" />
        </template>
      </el-table-column>
      <el-table-column
        label="申请单编号"
        align="center"
        prop="requestOrderCode"
        width="150"
      />
      <el-table-column label="客户" align="center" prop="cusName" />
      <el-table-column
        label="应出库数量"
        align="center"
        prop="outStockNum"
        width="180"
      />
      <el-table-column
        label="实际出库数量"
        align="center"
        prop="outStockNumber"
        width="180"
      />
      <el-table-column
        label="出库状态"
        align="center"
        prop="stockStatus"
        width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.stockStatus === 0" style="color: orange"
            >待出库</span
          >
          <span v-else-if="scope.row.stockStatus === 1" style="color: #409eff"
            >部分出库</span
          >
          <span v-else-if="scope.row.stockStatus === 2" style="color: green"
            >全部出库</span
          >
          <span v-else-if="scope.row.stockStatus === 3" style="color: red"
            >待补货</span
          >
        </template>
      </el-table-column>
      <el-table-column label="总价" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.total }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="成本价" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.costPrice }}元</span>
        </template>
      </el-table-column>
      <el-table-column
        label="收款状态"
        align="center"
        prop="payStatus"
        width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.payStatus === 0" style="color: orange"
            >待收款</span
          >
          <span v-else-if="scope.row.payStatus === 1" style="color: #409eff"
            >部分收款</span
          >
          <span v-else-if="scope.row.payStatus === 2" style="color: green"
            >全部收款</span
          >
          <span v-else-if="scope.row.payStatus === 3" style="color: red"
            >已挂帐</span
          >
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="实收金额" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.payMoney }}元</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="updateBy" />

      <el-table-column label="审批人" align="center" prop="updateBy" />
      <el-table-column
        label="审批时间"
        align="center"
        prop="updateDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.orderStatus === 0" style="color: orange"
            >已提交</span
          >
          <span v-else-if="scope.row.orderStatus === 1" style="color: #409eff"
            >审核通过</span
          >
          <span v-else-if="scope.row.orderStatus === 2" style="color: red"
            >驳回</span
          >
          <span v-else-if="scope.row.orderStatus === 3" style="color: red"
            >执行完</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding"
        fixed="right"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="shenhe(scope.row)"
            v-hasPermi="['xiaoshou:order:edit']"
            :disabled="scope.row.orderStatus !== 0"
            >审核</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['xiaoshou:order:remove']"
            >关闭</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加销售订单对话框 -->
    <el-dialog :title="title" :visible.sync="isAdd" width="70%" append-to-body>
      销售申请：<el-input
        placeholder="请选择销售申请单"
        @focus="getAllRequest"
        v-model="saleRequestCode"
      ></el-input>
      <el-dialog
        :title="title"
        :visible.sync="isShowAll"
        width="70%"
        append-to-body
      >
        <el-table v-loading="loading" :data="saleRequestList">
          <el-table-column fixed prop="code" label="单据编号">
            <template slot-scope="scope">
              <span style="color: orange" @click="chooseOrder(scope.row.id)">{{
                scope.row.code
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户" align="center" prop="cusName" />
          <el-table-column label="创建人" align="center" prop="createBy" />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createDate"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="审核人" align="center" prop="auditName" />
        </el-table>
      </el-dialog>
      <div v-if="showView">
        <el-descriptions>
          <el-descriptions-item
            label="单据编号"
            content-class-name="my-content"
          >
            <span style="color: #409eff">{{ orderView.code }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="单据日期">{{
            orderView.createDate
          }}</el-descriptions-item>
          <el-descriptions-item label="客户">{{
            orderView.cusName
          }}</el-descriptions-item>
          <el-descriptions-item label="业务员">{{
            orderView.createBy
          }}</el-descriptions-item>
          <el-descriptions-item label="总金额"
            >{{ totalPrice }}元</el-descriptions-item
          >
          <el-descriptions-item label="审批人">{{
            orderView.auditName
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <el-table :data="orderDetailList" border style="width: 100%">
        <el-table-column prop="proName" label="商品名"> </el-table-column>
        <el-table-column prop="count" label="数量"> </el-table-column>
        <el-table-column prop="unitName" label="单位"> </el-table-column>
        <el-table-column label="单价">
          <template slot-scope="scope"> {{ scope.row.price }} 元 </template>
        </el-table-column>
        <el-table-column label="小计">
          <template slot-scope="scope"> {{ scope.row.subtotal }} 元 </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addSaleOrder">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 审核弹框详情 -->
    <el-dialog
      title="审核订单 - 详情"
      :visible.sync="shenHeView"
      width="80%"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <div>
        <template>
          <div>
            <el-descriptions>
              <el-descriptions-item
                label="单据编号"
                content-class-name="my-content"
                >{{ data.code }}</el-descriptions-item
              >
              <el-descriptions-item label="单据日期">{{
                data.createDate
              }}</el-descriptions-item>
              <el-descriptions-item label="客户">{{
                data.cusName
              }}</el-descriptions-item>
              <el-descriptions-item label="业务员">{{
                data.createBy
              }}</el-descriptions-item>
              <el-descriptions-item label="出库状态">
                <span :style="getStatusStyle(data.stockStatus)">
                  {{ getStatusText(data.stockStatus) }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="付款状态">
                <span :style="getStatusStyle(data.payStatus)">
                  {{ getStatusText1(data.payStatus) }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="总金额"
                >{{ data.total }}元</el-descriptions-item
              >
              <el-descriptions-item label="申请订单审批人">{{
                data.auditName
              }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </template>
        <el-table :data="orderDetail" border style="width: 100%">
          <el-table-column prop="proName" label="商品名"></el-table-column>
          <el-table-column prop="number" label="数量"></el-table-column>
          <el-table-column prop="unitName" label="单位"></el-table-column>
          <el-table-column label="单价">
            <template slot-scope="scope"> {{ scope.row.price }} 元 </template>
          </el-table-column>
          <el-table-column prop="outStock" label="出库数量"></el-table-column>
          <el-table-column label="小计">
            <template slot-scope="scope">
              {{ scope.row.subtotal }} 元
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 审核状态选择框 -->
      <el-form label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="approval.approvalResult">
            <el-radio :label="1">同意</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input
            type="textarea"
            v-model="approval.approvalOption"
            placeholder="请输入审核意见"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="shenHeView = false">取 消</el-button>
        <el-button type="primary" @click="handleAudit">审核</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrder,
  addSaleOrder,
  updateSaleOrderStatus,
  saleOrderList,
  getAllRequest,
  saleRequestList,
  getSaleRequest,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
} from "@/api/xiaoshou/saleOrder";
import orderView from "./OrderView";
export default {
  name: "Order",
  components: { orderView },
  data() {
    return {
      data: {},
      shenHeView: false,
      totalPrice: 0,
      showView: false,
      orderView: {},
      orderDetailList: [],
      orderDetail: [],
      saleRequestCode: "",
      saleRequestList: [],
      isShowAll: false,
      isAdd: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      approval: {
        approvalResult: 2,
        approvalOption: "",
        code: "",
      },
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否删除(0:未删除 1:删除)时间范围
      daterangeCreateDate: [],
      // 是否删除(0:未删除 1:删除)时间范围
      daterangeUpdateDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        cusName: null,
        total: null,
        stockStatus: null,
        payStatus: null,
        createBy: null,
        createDate: null,
        updateBy: null,
        updateDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "订单编号不能为空", trigger: "blur" },
        ],
        cusName: [{ required: true, message: "客户不能为空", trigger: "blur" }],
        total: [{ required: true, message: "总价不能为空", trigger: "blur" }],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" },
        ],
        payMoney: [
          { required: true, message: "实收金额不能为空", trigger: "blur" },
        ],
        createDate: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleAudit() {
      if (this.auditResult === "") {
        this.$message.warning("请选择审核结果");
        return;
      }
      // 这里可以添加提交审核结果和意见的逻辑
      this.approval.code = this.data.code;
      console.log(this.approval);
      updateSaleOrderStatus(this.approval).then((response) => {
        if (response.code === 200) {
          this.$message.success("审核成功");
          this.shenHeView = false;
          this.getList();
        }
      });

      this.data = {};
      this.orderDetail = [];
      this.shenHeView = false;
    },
    appView(orderId) {
      this.dialogVisible = true;
      saleOrderList(orderId).then((response) => {
        this.orderDetail = response.data;
      });
    },
    shenhe(row) {
      this.data = row;
      this.shenHeView = true;
      this.appView(row.id);
    },
    getStatusText(status) {
      const statusMap = {
        0: "待出库",
        1: "部分出库",
        2: "全部出库",
      };
      return statusMap[status] || "未知状态";
    },
    getStatusText1(status) {
      const statusMap = {
        0: "待付款",
        1: "部分付款",
        2: "全部付款",
        3: "已挂帐",
      };
      return statusMap[status] || "未知状态";
    },
    getStatusStyle(status) {
      const statusMap = {
        0: "color: orange;",
        1: "color: green;",
        2: "color: #409eff;",
        3: "color: red;",
      };
      return statusMap[status] || "color: black;";
    },
    //展示销售订单详情
    showViewDetail(order) {
      this.orderView = order;
    },
    //添加销售订单
    addSaleOrder() {
      if (this.saleRequestCode == "") {
        alert("请选择订单引用");
        return;
      }
      addSaleOrder(this.orderView.id).then((res) => {
        alert(res.msg);
        this.isAdd = false;
        this.getList();
        this.cancel();
      });
    },
    //获取所有销售申请订单
    getAllRequest() {
      getAllRequest().then((response) => {
        this.saleRequestList = response.data;
        this.isShowAll = true;
      });
    },
    //选择订单
    chooseOrder(id) {
      this.isShowAll = false;
      getSaleRequest(id).then((response) => {
        this.orderView = response.data;
        this.saleRequestCode = this.orderView.code;
        this.showView = true;
        saleRequestList(id).then((response) => {
          this.orderDetailList = response.data;
          this.totalPrice = this.orderDetailList.reduce(
            (acc, item) => acc + item.subtotal,
            0
          );
        });
      });
    },
    /** 查询销售订单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateDate && "" != this.daterangeCreateDate) {
        this.queryParams.params["beginCreateDate"] =
          this.daterangeCreateDate[0];
        this.queryParams.params["endCreateDate"] = this.daterangeCreateDate[1];
      }
      if (null != this.daterangeUpdateDate && "" != this.daterangeUpdateDate) {
        this.queryParams.params["beginUpdateDate"] =
          this.daterangeUpdateDate[0];
        this.queryParams.params["endUpdateDate"] = this.daterangeUpdateDate[1];
      }
      listOrder(this.queryParams).then((response) => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.isAdd = false;
      this.totalPrice = 0;
      this.showView = false;
      (this.orderView = {}),
        (this.orderDetailList = []),
        (this.saleRequestCode = ""),
        (this.saleRequestList = []),
        this.reset();
    },

    // 表单重置
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        cusName: null,
        total: null,
        stockStatus: null,
        payStatus: null,
        createBy: null,
        payMoney: null,
        createDate: null,
        updateBy: null,
        updateDate: null,
        isDel: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateDate = [];
      this.daterangeUpdateDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isAdd = true;
      this.title = "选择销售申请订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOrder(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改销售订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认关闭销售订单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrder(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("关闭成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "xiaoshou/order/export",
        {
          ...this.queryParams,
        },
        `order_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
